#include "udpclient.h"

using namespace std;

UDPclient::UDPclient()
{

}
void UDPclient::socket(char *argv[])
{
    sockfd = ::socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0) error("socket");
    server.sin_family = AF_INET;
    hp = gethostbyname(argv[1]);
    if (hp==0) error("Unknown host");

    bcopy((char *)hp->h_addr,
          (char *)&server.sin_addr,
          hp->h_length);
    server.sin_port = htons(atoi(argv[2]));
    length=sizeof(struct sockaddr_in);
}

void UDPclient::checkConnection(int argc)

{
    if (argc != 3)
    {
        cout<<"ERROR, falta la ip del servidor o el puerto"<<endl;
        exit(1);
    }
}

void UDPclient::enviar(string buffer)
{
    bufferString2Char(buffer);
    n=sendto(sockfd,cbuffer,strlen(cbuffer),0,(const struct sockaddr *)&server,length);
    if (n < 0) error("Sendto");
}

void UDPclient::recibir()
{
    bzero(ccbuffer,1024);
    n = recvfrom(sockfd,ccbuffer,1024,0,(struct sockaddr *)&from, &length);
    if (n < 0) error("recvfrom");
    bufferChar2String(ccbuffer);
}
